package com.epkursant.app.mail;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.ep.general.app.Utils;
import com.ep.general.kursant.Kursant;
import com.ep.general.kursant.KursantMdt;
import com.opensymphony.xwork2.ActionSupport;

public class SendMail extends ActionSupport {

	private static final long serialVersionUID = -5651944591462756043L;

	private KursantMdt kursantMdt;
	private Kursant kursant;

	private String from;
	private String password;
	private String email;
	private String subject;
	private String body;

	static Properties properties = new Properties();
	static {
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.socketFactory.port", "465");
		properties.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.port", "465");
	}

	public String toPage() {
		return "toPage";
	}

	public String execute() {
		from = "dawid.eprawojazdy@gmail.com";
		password = "eprawojazdy";
		subject = "E-PrawoJazdy";

		// random new password
		SecureRandom random = new SecureRandom();
		String newPassword = new BigInteger(30, random).toString(32);

		body = "Twoje nowe hasło do Platformy E-PrawoJazdy to: <br><br><h3>"
				+ newPassword
				+ "</h3> <br><br>Zalecamy po ponownym zalogowaniu zmienić je.";

		try {
			Session session = Session.getDefaultInstance(properties,
					new javax.mail.Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(from, password);
						}
					});

			kursant = getKursantMdt().getByEmail(email);
			if (kursant != null) {
				kursant.setHaslo(Utils.convertToMd5(newPassword));
				getKursantMdt().makePersistent(kursant);

				Message message = new MimeMessage(session);
				message.setFrom(new InternetAddress(from));
				message.setRecipients(Message.RecipientType.TO,
						InternetAddress.parse(email));
				message.setSubject(subject);

				// message
				message.setContent(body, "text/html;charset=UTF-8");
				Transport.send(message);
			} else {
				addActionError("Niepoprawy e-mail");
				return ERROR;
			}

		} catch (Exception e) {
			addActionError("Usługa chwilowo niedostępna");
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public static Properties getProperties() {
		return properties;
	}

	public static void setProperties(Properties properties) {
		SendMail.properties = properties;
	}

	private KursantMdt getKursantMdt() {
		if (kursantMdt == null)
			kursantMdt = new KursantMdt();
		return kursantMdt;
	}

}
